<template>
	<Dialog v-model="dialogVisible" :title="dialogTitle">
		<el-form
				ref="formRef"
				v-loading="formLoading"
				:model="formData"
				:rules="formRules"
				label-width="80px"
		>
			<el-form-item label="上传文件" prop="org">
				<UploadFile v-model="formData.fileUrl" :limit="1" :file-size="100" class="min-w-80px"/>
			</el-form-item>
			<el-form-item label="职能" prop="org">
				<el-select v-model="formData.org" placeholder="请选择职能" size="large" @change="orgChange">
					<el-option v-for="(item, index) in orgList" :key="index" :label="item" :value="item"/>
				</el-select>
			</el-form-item>
			<el-form-item label="职级" prop="level">
				<el-select v-model="formData.level" placeholder="请选择职级" size="large">
					<el-option v-for="(item, index) in levelList" :key="index" :label="item" :value="item"/>
				</el-select>
			</el-form-item>
			<el-form-item label="文件名称" prop="fileName">
				<el-input v-model="formData.fileName" placeholder="请输入文件名称"/>
			</el-form-item>
			<el-form-item label="文件ID">
				<el-input v-model="formData.id" placeholder="创建后生成" disabled/>
			</el-form-item>
			<el-form-item label="创建时间">
				<el-input v-model="formData.createTime" placeholder="创建后生成" disabled/>
			</el-form-item>
			<el-form-item label="发布人">
				<el-input v-model="formData.userName" placeholder="创建后生成" disabled/>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="dialogVisible = false">取 消</el-button>
			<el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
		</template>
	</Dialog>
</template>
<script lang="ts" setup>
import * as RoleApi from '@/api/system/role'
import {GetOrgList, GetLevelList} from '@/api/system/org'
import {getDocCreate, getDocPut, getDoc} from '@/api/system/my-doc'
import {useCache, CACHE_KEY} from '@/hooks/web/useCache'

const {wsCache} = useCache()


defineOptions({name: 'SystemRoleForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  org: '',
  level: '',
  fileName: '',
  fileUrl: ''
})
const formRules = reactive({
  org: [{required: true, message: '职能不能为空', trigger: 'change'}],
  level: [{required: true, message: '职级不能为空', trigger: 'change'}],
  fileName: [{required: true, message: '文件名称不能为空', trigger: 'blur'}],
  fileUrl: [{required: true, message: '文件不能为空', trigger: 'change'}]
})
const formRef = ref() // 表单 Ref

// 职能列表
const orgList = ref([])
const apiGetOrgList = async () => {
  orgList.value = await GetOrgList()
}

const orgChange = () => {
  if (formData.value.level) formData.value.level = ''
  apiGetLevelList()
}

// 职级列表
const levelList = ref([])
const apiGetLevelList = async () => {
  levelList.value = await GetLevelList(formData.value.org)
}


const defaultOrgLevel = () => {
  const userInfo = wsCache.get(CACHE_KEY.USER)
  formData.value.org = userInfo.user.org;
  formData.value.level = userInfo.user.level
  
  apiGetLevelList()
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await apiGetOrgList()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await getDoc(id)
    } finally {
      formLoading.value = false
    }
  } else defaultOrgLevel()
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    org: '',
    level: '',
    fileName: '',
    fileUrl: ''
  }
  formRef.value?.resetFields()
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RoleApi.RoleVO
    if (formType.value === 'create') {
      await getDocCreate(data)
      message.success(t('common.createSuccess'))
    } else {
      await getDocPut(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>
